package cn.westv.scps.connTools;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

import cn.westv.scps.constant.ConfigCodeConstant;
import cn.westv.scps.constant.DBconstant;
import cn.westv.scps.domain.AreaSeverEntity;
import cn.westv.scps.domain.BikeOwnerEntity;
import cn.westv.scps.domain.PublishAgentEntity;
import cn.westv.scps.exception.ConnException;
import cn.westv.scps.service.areaserver.IAreaServerService;
import cn.westv.scps.service.bikeowner.IBikeOwnerService;
import cn.westv.scps.service.sys.config.ISysConfigService;
import cn.westv.scps.utils.SpringContextUtil;

/**
 * 封装了所有连接base服务器的http方法
 * 
 * @author Administrator
 *
 */
public class ProxyConnExec {
	// @Resource
	// private IAreaServerService areaServerService;

	private static boolean refreshKey = true;
	private static boolean refreshToken = true;
	private static Map<String, String> tokenMap = new HashMap<String, String>();
	private static Logger log = Logger.getLogger(ProxyConnExec.class);
	public static Map<String, String> modulusMap = new HashMap<String, String>();
	private static Map<String, String> public_exponentMap = new HashMap<String, String>();

	/**
	 * 拼接需要传的参数
	 * 
	 * @param paramMap
	 * @return
	 */
	public static String jointParams(Map<String, Object> paramMap) {
		String paramStr = "";
		Set<Entry<String, Object>> entrySet = paramMap.entrySet();
		for (Entry<String, Object> entry : entrySet) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if (!StringUtils.isEmpty(paramStr)) {
				paramStr += "&";
			}
			paramStr += (key + "=" + value);
		}
		return paramStr;
	}

	/**
	 * 根据areaSeverEntity获取对应的公钥
	 * 
	 * @param areaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> getPublicKeyBySNcode(AreaSeverEntity areaSeverEntity) throws Exception {
		String modulus = getModulusByContextPath(areaSeverEntity);
		String publicExponent = getPublicExponent(areaSeverEntity);
		Map<String, String> map = new HashMap<String, String>();
		map.put("modulus", modulus);
		map.put("publicExponent", publicExponent);
		return map;
	}

	/**
	 * 向服务器发送请求的方法
	 * 
	 * @param actUrl
	 * @param json
	 * @param AreaSeverEntity
	 * @param needToke
	 * @param retry
	 *            第一次失败后，再次尝试的次数
	 * @return
	 * @throws Exception
	 */
	private static JSONObject exec(String actUrl, String params, AreaSeverEntity AreaSeverEntity, boolean needToke,
			int retry) throws Exception {
		if (retry < 0) {
			throw new ConnectException("多次尝试连接服务器后失败！");
		}
		int responseCode = 0;
		String rs = "";
		String surl = "";
		if (needToke) {
			int indexOf = actUrl.indexOf("?");
			if (indexOf == -1) {
				surl += actUrl + "?token=" + getToken(AreaSeverEntity);
			} else {
				surl += actUrl + "&token=" + getToken(AreaSeverEntity);
			}
		} else {
			surl += actUrl;
		}
		URL url = new URL(surl);
		HttpURLConnection http = (HttpURLConnection) url.openConnection();

		http.setRequestMethod("POST");
		http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		http.setRequestProperty("Accept-Charset", "UTF-8");
		if (StringUtils.isNotBlank(params)) {
			http.setDoOutput(true);
			// http.setChunkedStreamingMode(1024 * 1024);
		}
		http.setDoInput(true);
		System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
		System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
		try {
			http.connect();
			if (StringUtils.isNotBlank(params)) {
				OutputStream os = null;
				try {
					os = http.getOutputStream();
					os.write(params.getBytes("UTF-8"));// 传入参数
					os.flush();
				} catch (Exception e) {
					throw new RuntimeException(e);
				} finally {
					if (os != null)
						os.close();
				}
			}
			responseCode = http.getResponseCode();
			log.debug("请求状态码：" + responseCode);
			JSONObject jobj = null;
			if (responseCode == 200) {
				InputStream is = null;
				try {
					is = http.getInputStream();
					int size = is.available();
					List<String> list = new ArrayList<String>();
					byte[] jsonBytes = new byte[size];
					int len = 0;
					while ((len = is.read(jsonBytes)) != -1) {
						String str = new String(jsonBytes, 0, len, "UTF-8");
						list.add(str);
						// System.out.println(str);
						// System.out.println(list.size());
						jsonBytes = new byte[size];
					}
					for (String str : list) {
						rs += str;
					}
					log.debug("服务器返回的信息是：" + rs);
					int indexOf = rs.indexOf(":");
					if (indexOf == -1) {
						rs = "{data:" + rs + "}";
					}
					jobj = JSONObject.parseObject(rs);
					log.debug(jobj);

				} catch (Exception e) {
					throw new RuntimeException(e);
				} finally {
					is.close();
					// http.disconnect();
				}
				return jobj;
			}
			if (responseCode == 404) {
				throw new ConnException("服务器连接404");
			}
			if (responseCode == 401) {
				refreshKey = true;
				refreshToken = true;
				retry--;
				return exec(actUrl, params, AreaSeverEntity, needToke, retry);// 应为401的情况很可能是token过期找出的，所以需要重新获取一次钥匙，所以这里是retry--
			}
		} catch (ConnectException e) {
			log.debug("服务器无响应！");
			if (retry < 0) {
				throw new ConnException("服务器连接404");
			} else {
				return exec(actUrl, params, AreaSeverEntity, needToke, --retry);
			}
		} catch (Exception e1) {
			throw new RuntimeException(e1);
		} finally {
			http.disconnect();
		}
		return null;

	}

	/**
	 * 对数据进行加密处理
	 * 
	 * @param account
	 * @param contextPath
	 * @return
	 * @throws Exception
	 */
	public static String encData(String data, AreaSeverEntity AreaSeverEntity) throws Exception {
		String modulus = getModulusByContextPath(AreaSeverEntity);
		String publicExponent = getPublicExponent(AreaSeverEntity);
		String encData = RSAClientUtils.encryptByPublicKey(modulus, publicExponent, data);
		return encData;
	}

	/**
	 * 根据contextPath获取对应的token
	 * 
	 * @param contextPath
	 * @return
	 * @throws Exception
	 */
	private static String getToken(AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		if (refreshToken) {
			refreshToken(AreaSeverEntity);
		}

		String token = tokenMap.get(contextPath);
		return token;
	}

	/**
	 * 向服务器发送请求获取token
	 * 
	 * @param contextPath
	 * @throws Exception
	 */
	private static void refreshToken(AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String proxy_id = AreaSeverEntity.getProxyId();
		String proxy_secret = AreaSeverEntity.getProxySecret();
		if (StringUtils.isEmpty(proxy_id) || StringUtils.isEmpty(proxy_secret)) {
			return;
		}
		if (refreshToken) {
			String encID = encData(proxy_id, AreaSeverEntity);
			String encSecret = encData(proxy_secret, AreaSeverEntity);
			String actUrl = contextPath + "/s/px/login";
			String params = "proxyid=" + encID + "&proxySecret=" + encSecret;
			JSONObject jobj = exec(actUrl, params, AreaSeverEntity, false, 3);
			if (jobj != null && jobj.getString("opStatus").equals("0")) {
				refreshToken = false;
				tokenMap.put(contextPath, jobj.getString("data"));
				log.debug("proxy向服务器请求的token：" + jobj.getString("data"));
			}
			if (jobj.getString("opStatus").equals("keyErr")) {
				refreshKey = true;
				getPublicKey(AreaSeverEntity);
				refreshToken(AreaSeverEntity);
			}
		}

	}

	/**
	 * 向服务器发送请求获取公钥
	 * 
	 * @param contextPath
	 * @return
	 * @throws Exception
	 */
	private static void getPublicKey(AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		if (refreshKey) {
			String actUrl = contextPath + "/s/not/loginaction";
			JSONObject jobj = exec(actUrl, null, AreaSeverEntity, false, 3);
			if (jobj.getString("opStatus").equals("0")) {
				JSONObject data = (JSONObject) jobj.get("data");
				modulusMap.put(contextPath, data.getString("modulus"));
				public_exponentMap.put(contextPath, data.getString("public_exponent"));
				refreshKey = false;
			}
		}
		return;

	}

	/**
	 * 根据contextPath获取对应的模指数
	 * 
	 * @param contextPath
	 * @return
	 * @throws Exception
	 */
	private static String getModulusByContextPath(AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		if (refreshKey) {
			getPublicKey(AreaSeverEntity);
		}
		String modulus = modulusMap.get(contextPath);
		if (StringUtils.isEmpty(modulus)) {
			refreshKey = true;
			getPublicKey(AreaSeverEntity);
			return modulusMap.get(contextPath);
		}
		return modulus;

	}

	/**
	 * 根据contextPath获取对应服务器的公钥指数
	 * 
	 * @param contextPath
	 * @return
	 * @throws Exception
	 */
	private static String getPublicExponent(AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		if (refreshKey) {
			getPublicKey(AreaSeverEntity);
		}
		String public_exponent = public_exponentMap.get(contextPath);
		if (StringUtils.isEmpty(public_exponent)) {
			refreshKey = true;
			getPublicKey(AreaSeverEntity);
			return public_exponentMap.get(contextPath);
		}
		return public_exponent;
	}

	/**
	 * owner用户请求认证
	 * 
	 * @param account
	 * @param password
	 * @param contextPath
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject ownerLogin(String account, String password, AreaSeverEntity AreaSeverEntity)
			throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/px/owner";
		String params = "account=" + account + "&password=" + password;
		JSONObject jobj = exec(actUrl, params, AreaSeverEntity, true, 3);
		if (jobj.get("opStatus").equals("keyErr")) {
			refreshKey = true;
			String encAccount = ProxyConnExec.encData(account, AreaSeverEntity);
			String encPassword = ProxyConnExec.encData(password, AreaSeverEntity);
			return ownerLogin(encAccount, encPassword, AreaSeverEntity);
		}
		return jobj;
	}

	/**
	 * 根据ownerId获取车主用户的所有车辆信息
	 * 
	 * @param ownerToken
	 *            用户登录成功后，cloud_base服务器返回的token
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject findByOwnerIdGroupAndTag(String ownerId, AreaSeverEntity AreaSeverEntity)
			throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/registation/listtags?ownerId=" + ownerId;
		JSONObject exec = exec(actUrl, null, AreaSeverEntity, true, 3);
		return exec;
	}

	/**
	 * 锁车
	 * 
	 * @param ownerToken
	 * @param regiId
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject setProtect(String regiId, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/registation/protect?regiId=" + regiId;
		JSONObject exec = exec(actUrl, null, AreaSeverEntity, true, 3);
		return exec;
	}

	/**
	 * 将车辆解锁
	 * 
	 * @param ownerToken
	 * @param regiId
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject setUnProtect(String regiId, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/registation/unprotect?regiId=" + regiId;
		JSONObject exec = exec(actUrl, null, AreaSeverEntity, true, 3);
		return exec;
	}

	/**
	 * 车辆手动报警
	 * 
	 * @param ownerToken
	 * @param regiId
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject ownerReport(String regiId, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/blacklist/ownerreport?regiId=" + regiId;
		JSONObject exec = exec(actUrl, null, AreaSeverEntity, true, 3);
		return exec;
	}

	/**
	 * 销警
	 * 
	 * @param ownerToken
	 * @param blacklistId
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject changeToRetrive(String blacklistId, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/blacklist/retrive?blacklistId=" + blacklistId;
		JSONObject exec = exec(actUrl, null, AreaSeverEntity, true, 3);
		return exec;
	}

	/**
	 * 获取黑名单列表
	 * 
	 * @param vo
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject blackList(String regiId, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/blacklist/list";
		String params = "page=1&rows=999999&notInState=5,6";
		if (StringUtils.isNotBlank(regiId)) {
			params += "&regiId=" + regiId;
		} else {
			return null;
		}
		JSONObject exec = exec(actUrl, params, AreaSeverEntity, true, 3);
		return exec;
	}

	/**
	 * manTag查询标签位置
	 * 
	 * @param manTag
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject getManTagMarkerByTag(String manTag, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/mobiletag/marker/" + manTag;
		JSONObject exec = exec(actUrl, null, AreaSeverEntity, true, 3);
		return exec;
	}

	/**
	 * gps查询标签位置
	 * 
	 * @param gprsImei
	 * @param AreaSeverEntity
	 * @param mapType
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject getGprsImeiMarkerByTag(String gprsImei, AreaSeverEntity AreaSeverEntity, String mapType)
			throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/gprs/marker/" + gprsImei + "?mapType=" + mapType;
		JSONObject exec = exec(actUrl, null, AreaSeverEntity, true, 3);
		return exec;
	}

	/**
	 * 获取gps的轨迹坐标点
	 * 
	 * @param gprsImei
	 * @param timeBegin
	 *            yyyy-MM-dd HH:mm
	 * @param timeEnd
	 *            yyyy-MM-dd HH:mm
	 * @param mapType
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject getGprsPath(String gprsImei, String timeBegin, String timeEnd, String mapType,
			AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		/// s/gprs/path/${gprsImei}?mapType=baidu&timeBegin=&timeEnd=yyyy-MM-dd
		/// HH:mm
		String actUrl = contextPath + "/s/gprs/path/" + gprsImei;
		String params = "mapType=" + mapType + "&timeBegin=" + timeBegin + "&timeEnd=" + timeEnd;
		return exec(actUrl, params, AreaSeverEntity, true, 3);
	}

	/**
	 * RFID轨迹查询
	 * 
	 * @param manTag
	 * @param timeBegin
	 * @param timeEnd
	 * @param mapType
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject getRfidPath(String mainTag, String timeBegin, String timeEnd, String mapType,
			AreaSeverEntity AreaSeverEntity) throws Exception {
		/// mobiletag/path/{groupId}/{tagId}
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/mobiletag/path/" + "1/" + mainTag;
		String params = "mapType=" + mapType + "&&timeBegin=" + timeBegin + "&timeEnd=" + timeEnd;
		return exec(actUrl, params, AreaSeverEntity, true, 3);
	}

	/**
	 * 告警历史
	 * 
	 * @param ownerToken
	 * @param vo
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject abnormalList(String ownerId, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/abnormal/list";
		String params = "page=1&rows=9999999&ownerId=" + ownerId;
		JSONObject exec = exec(actUrl, params, AreaSeverEntity, true, 3);
		return exec;
	}

	/**
	 * 刷新base服务器的系统时间
	 * 
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject synctime(String dataTime, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		log.info(contextPath);
		String actUrl = contextPath + "/s/common/synctime";
		String param = "dateTime=" + dataTime;
		return exec(actUrl, param, AreaSeverEntity, true, 3);
	}

	/**
	 * 获取当前的时间戳
	 * 
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject getCrunTime() throws Exception {
		String actUrl = "http://www.114time.com/api/time.php";
		return exec(actUrl, null, null, false, 3);
	}

	/**
	 * 校验账号是否存在
	 * 
	 * @param account
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject existowner(String account, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/owner/existowner?account=" + account;
		return exec(actUrl, null, AreaSeverEntity, true, 3);
	}

	/**
	 * 告知base服务器微信和用户绑定
	 * 
	 * @param ownerId
	 * @param wechatId
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject wechatbind(String ownerId, String wechatId, AreaSeverEntity AreaSeverEntity)
			throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/owner/wechatbind";
		String param = "ownerId=" + ownerId + "&wechatId=" + wechatId;
		return exec(actUrl, param, AreaSeverEntity, true, 3);
	}

	/**
	 * 告知base服务器微信和用户解绑
	 * 
	 * @param ownerId
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject wechatunbind(String ownerId, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/owner/wechatunbind";
		String param = "ownerId=" + ownerId;
		return exec(actUrl, param, AreaSeverEntity, true, 3);
	}

	/**
	 * 车主确认找回车辆
	 * 
	 * @param blacklistId
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	public static JSONObject blacklistRetrive(String blacklistId, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/blacklist/retrive?blacklistId=" + blacklistId;
		return exec(actUrl, null, AreaSeverEntity, true, 3);
	}

	/**
	 * 根据邀请码获取用户ownerId
	 *
	 * @param license
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getOwnerIdByApplayCode(String license, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/owner/applay/" + license;
		return exec(actUrl, null, AreaSeverEntity, true, 3);
	}

	/**
	 * 根据邀请码获取用户ownerId
	 * 
	 * @param license
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getOwnerInfoByApplayCode(String invitationCode, AreaSeverEntity AreaSeverEntity)
			throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/owner/getowner/" + invitationCode;
		return exec(actUrl, null, AreaSeverEntity, true, 3);
	}

	/**
	 * 获取需要购买保险详细名单
	 * 
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getPurchaseInsuranceList(AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/registation/unisurance";
		String params = null;
		JSONObject exec = exec(actUrl, params, AreaSeverEntity, true, 3);
		return exec;
	}

	/**
	 * 告知服务器购买保险邮件发送成功
	 * 
	 * @param param
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject updateIsurance(String regiIdJsonStr, AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/registation/update/isurance";
		String param = "param=" + regiIdJsonStr;
		JSONObject exec = exec(actUrl, param, AreaSeverEntity, true, 3);
		return exec;

	}

	// /**
	// * 用户注册
	// *
	// * @param ownerId
	// * @param account
	// * @param password
	// * @param AreaSeverEntity
	// * @return
	// * @throws Exception
	// */
	// @Deprecated
	// public static JSONObject ownerRegist(String ownerId, String account,
	// String password,
	// AreaSeverEntity AreaSeverEntity) throws Exception {
	// String contextPath = AreaSeverEntity.getContextPath();
	// String actUrl = contextPath + "/s/owner/regist/" + ownerId;
	// account = encData(account, AreaSeverEntity);
	// password = encData(password, AreaSeverEntity);
	// String param = "account=" + account + "&password=" + password;
	// return exec(actUrl, param, AreaSeverEntity, true,3);
	// }

	/**
	 * 用户注册
	 * 
	 * @param invitationCode
	 * @param account
	 * @param password
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject ownerRegistSubmit(String invitationCode, String account, String password,
			AreaSeverEntity AreaSeverEntity) throws Exception {
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/owner/newregist/" + invitationCode;
		// account = encData(account, AreaSeverEntity);
		// password = encData(password, AreaSeverEntity);
		String param = "account=" + account + "&password=" + password;
		JSONObject exec = exec(actUrl, param, AreaSeverEntity, false, 3);
		if (exec != null) {
			String opStatus = exec.getString("opStatus");
			if ("2".equals(opStatus)) {
				return ownerRegistSubmit(invitationCode, account, password, AreaSeverEntity);
			}
		}
		return exec;
	}

	/**
	 * 忘记密码
	 * 
	 * @param account
	 * @param password
	 * @param AreaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject forgetPassword(String mobile, String password, String isWechat,
			AreaSeverEntity AreaSeverEntity) throws Exception {
		// mobile = ProxyConnExec.encData(mobile, AreaSeverEntity);
		// password = ProxyConnExec.encData(password, AreaSeverEntity);
		String contextPath = AreaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/owner/forgetpsw/app";
		// String param = "mobile=" + mobile + "&psw=" + password + "&isWechat="
		// + isWechat;
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("mobile", mobile);
		paramMap.put("psw", password);
		paramMap.put("isWechat", isWechat);
		return exec(actUrl, jointParams(paramMap), AreaSeverEntity, true, 3);
	}

	/**
	 * 根据手机号码和token验证用户的手机号码和token是否对应
	 * 
	 * @param token
	 * @param mobile
	 * @return
	 * @throws Exception
	 */
	public static JSONObject mobileVerify(String token, String mobile, AreaSeverEntity areaSeverEntity)
			throws Exception {
		String contextPath = areaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/owner/mobileverify";
		String param = "mobile=" + mobile + "&token=" + token;
		return exec(actUrl, param, areaSeverEntity, false, 3);
	}

	/**
	 * 用户修改手机的接口
	 * 
	 * @param token
	 * @param oldMobile
	 * @param newMobile
	 * @param areaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject changeMobile(String isWechat, String token, String oldMobile, String newMobile, String password,
			String client, AreaSeverEntity areaSeverEntity) throws Exception {
		if(StringUtils.isEmpty(isWechat)){
			isWechat = "NO";
		}
		String contextPath = areaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/owner/changemobile";
		String param = "client=" + client + "&newMobile=" + newMobile + "&oldMobile=" + oldMobile + "&psw=" + password
				+ "&token=" + token + "&isWechat=" + isWechat;
		return exec(actUrl, param, areaSeverEntity, false, 3);
	}

	/**
	 * 向cloudbase服务器发送更新后的系统消息表
	 * 
	 * @param jsonArr
	 * @param areaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject synchronismUpdateSysMessageToCloudBase(String jsonArr, AreaSeverEntity areaSeverEntity)
			throws Exception {
		String contextPath = areaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/sysmessage/updateall";
		String encode = URLEncoder.encode(jsonArr, "UTF-8");
		String param = "jsonArr=" + encode;
		return exec(actUrl, param, areaSeverEntity, true, 3);
	}

	/**
	 * 遍历所有服务器，查找代理服务器不存在的用户
	 * 
	 * @param account
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getOwnerDatum(String account) throws Exception {
		IAreaServerService areaServerService = (IAreaServerService) SpringContextUtil.getBean("areaServerServiceImpl");
		List<AreaSeverEntity> serverlist = areaServerService.find("from AreaSeverEntity where done <> ?",
				AreaSeverEntity.class, new Object[] { DBconstant.DONE_SERVER });
		for (AreaSeverEntity areaSeverEntity : serverlist) {
			String contextPath = areaSeverEntity.getContextPath();
			String actUrl = contextPath + "/s/owner/ownerdatum";
			String param = "account=" + account;
			try {
				JSONObject exec = exec(actUrl, param, areaSeverEntity, true, 3);

				String opStatus = exec.getString("opStatus");
				if ("0".equals(opStatus)) {
					BikeOwnerEntity owner = new BikeOwnerEntity();
					owner.setAccount(exec.getJSONObject("data").getString("account"));
					owner.setMobile(exec.getJSONObject("data").getString("mobile"));
					owner.setAreaSever(areaSeverEntity);
					IBikeOwnerService bikeOwnerService = (IBikeOwnerService) SpringContextUtil
							.getBean("bikeOwnerServiceImpl");
					owner.setBikeOwnerId(null);
					bikeOwnerService.saveOrUpdate(owner);
					return exec;

				}
			} catch (Exception e) {
				e.printStackTrace();
				continue;

			}
		}
		return null;
	}

	/**
	 * 获取天气的json数据
	 * 
	 * @param key
	 *            api_key
	 * @param location
	 *            地点
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getWeather(String key, String location, String url) throws Exception {
		String params = "key=" + key + "&city=" + location;
		return exec(url, params, null, false, 3);
	}

	/**
	 * 从cloudBase服务器获取用户数据
	 * 
	 * @param phone
	 * @param areaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getOwnerToCloudbase(String mobile, AreaSeverEntity areaSeverEntity) throws Exception {
		String contextPath = areaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/owner/ownerdatum";
		String param = "account=" + mobile;
		return exec(actUrl, param, areaSeverEntity, true, 3);
	}

	/**
	 * 车主用户接触车辆绑定
	 * 
	 * @param token
	 * @param regiId
	 * @param areaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject registatioNunbind(String token, String regiId, AreaSeverEntity areaSeverEntity)
			throws Exception {
		String contextPath = areaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/registation/unbind";
		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("regiId", regiId);
		String param = jointParams(map);
		// String param = "regiId=" + regiId + "&token=" + token;
		return exec(actUrl, param, areaSeverEntity, false, 3);
	}

	/**
	 * 发送微信消息
	 */

	public static JSONObject sendWechatTxtMsg(String openid, String msg) throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("openid", openid);
		map.put("msg", msg);
		ISysConfigService sysConfigService = (ISysConfigService) SpringContextUtil.getBean("sysConfigServiceImpl");
		String contextPath = sysConfigService.findByCode(ConfigCodeConstant.WECHAT_PATH).getValue();
		return exec(contextPath + "/s/main/send/txtmsg", jointParams(map), null, false, 3);
	}

	/**
	 * 添加/修改代理商用户到base服务器
	 * 
	 * @param publishAgentEntity
	 * @param areaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject savePublishAgentUser(PublishAgentEntity publishAgentEntity,
			AreaSeverEntity areaSeverEntity) throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("userName", publishAgentEntity.getAgentName());
		map.put("phoneNum", publishAgentEntity.getPhoneNumber());
		map.put("address", publishAgentEntity.getAddress());
		map.put("account", publishAgentEntity.getAccount());
		map.put("password", publishAgentEntity.getPassword());
		map.put("userId", publishAgentEntity.getIdentity());
		String contextPath = areaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/sys/user/proxyadd";
		return exec(actUrl, jointParams(map), areaSeverEntity, true, 3);
	}

	/**
	 * 批量删除代理商用户
	 * 
	 * @param userIds
	 * @param areaSeverEntity
	 * @return
	 * @throws Exception
	 */
	public static JSONObject delPublishAgentUser(String userIds, AreaSeverEntity areaSeverEntity) throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("userIds", userIds);
		String contextPath = areaSeverEntity.getContextPath();
		String actUrl = contextPath + "/s/sys/user/remove";
		return exec(actUrl, jointParams(map), areaSeverEntity, true, 3);
	}
}
